package com.wistech.search.solr.extend.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wistech.search.solr.extend.dao.CompanyDao;
import com.wistech.search.solr.extend.model.Company;

@Service
public class CompanyManager {
	@Autowired
	private CompanyDao companyDao;
	private Map<String, Float> scores = new ConcurrentHashMap<String, Float>();

	public Company getCompany(String id) {
		return companyDao.get(id);
	}

	public void saveCompany(Company company) {
		companyDao.save(company);
		// 更新cache中的score
		if (company.getScore() != 0f) {
			scores.put(company.getId(), company.getScore());
		} else {
			scores.remove(company.getId());
		}
	}

	public List<String> findOnlineCompanyIds() {
		return companyDao.findCompanyIdsByOnline(true);
	}

	public void deleteCompany(String id) {
		if (id == null)
			return;
		companyDao.delete(id);
		scores.remove(id);
	}

	@PostConstruct
	public void loadCompanyScores() {
		Map<String, Float> scores = new ConcurrentHashMap<String, Float>();
		scores.putAll(companyDao.getAllScores());
		this.scores = scores;
	}

	public float getCompanyScore(String id) {
		Float score = scores.get(id);
		if (score != null) {
			return score;
		} else {
			score = companyDao.getScore(id);
			if (score == null) {
				return 0f;
			}
			scores.put(id, score);
			return score;
		}

	}
}
